/*
 *  Clocker.cpp
 *  Simple timer wrapper
 *
 *  Created by Michah Lerner on 8/5/08.
 *  Copyright 2008. All rights reserved.
 *
 */

#include "Clocker.h"

void Clocker::begin() {
	usageStart = clock() * CLOCKS_PER_SEC;
	gettimeofday(&start, NULL);
}

void Clocker::end() {
	usageEnd = clock() * CLOCKS_PER_SEC;
	gettimeofday(&stop, NULL);
}

double Clocker::getTimediff() {
	long dsec = stop.tv_sec - start.tv_sec;
	long usec = stop.tv_usec - start.tv_usec;
	return (1000000* dsec + usec) / 1E6;
}

unsigned long Clocker::getUsage() {
	return (usageEnd - usageStart) / 10000;
}

string Clocker::tod() {
	timeval tv;
	gettimeofday(&tv, NULL);
	char *buffer = (char *) malloc(30);
	strftime(buffer, 20, "%Y/%m/%d %H:%M:%S", localtime(&tv.tv_sec));
	ostringstream ostr;
	ostr << string(buffer) << '.' << setfill('0') << setw(6) << tv.tv_usec << ends;
	free(buffer);
	return ostr.str();
}

string Clocker::readAndReset() {
	ostringstream str;
	end();
	double diff = getTimediff();
	long usage = getUsage();
	str << " :: " << tod() << " :: " << setfill('0') << setprecision(6) << setw(10) << diff << " sec elapsed. "
	<< setfill(' ') << setw(10) << usage << " mUsec used";

	begin();
	return str.str();
}

